﻿using System;
using System.Linq;
using System.ServiceModel;
using System.Transactions;
using MouseExtender.WebSite.Logic.DataEntities;
using MouseExtender.WebSite.Logic.Managers;

namespace MouseExtender.WebSite.Logic.Services
{
    [ServiceContract]
    public class UpdateService
    {
        [OperationContract]
        public UpdateInfoEntity IsNewVersionAvailable(ApplicationInfo appVersionInfo)
        {
            using (TransactionScope scope = new TransactionScope())
            {
                using (MEDBDataContext medb = new MEDBDataContext())
                {
                    appVersionInfo.LastUpdateCheck = DateTime.Now;

                    var existentAppInfoQuery =
                        from a in medb.ApplicationInfos
                        where a.ApplicationInstanceId == appVersionInfo.ApplicationInstanceId
                        select a;

                    var existentAppInfo = existentAppInfoQuery.SingleOrDefault();
                    if (existentAppInfo == null)
                    {
                        appVersionInfo.FirstUpdateCheck = appVersionInfo.LastUpdateCheck;
                        medb.ApplicationInfos.InsertOnSubmit(appVersionInfo);
                    }
                    else
                    {
                        existentAppInfo.ApplicationVersion = appVersionInfo.ApplicationVersion;
                        existentAppInfo.LastUpdateCheck = appVersionInfo.LastUpdateCheck;
                    }

                    medb.SubmitChanges();
                    scope.Complete();
                }
            }

            var updateInfo = new UpdateManager().CheckForUpdates(new Version(appVersionInfo.ApplicationVersion));
            return updateInfo;

        }
    }
}
